package com.doublefish.doublefishrobot.ui.home;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.doublefish.doublefishrobot.R;
import com.doublefish.doublefishrobot.base.BaseActivity;
import com.doublefish.doublefishrobot.ui.home.adapter.AddDeviceListAdapter;
import com.doublefish.doublefishrobot.ui.home.bean.DeviceBean;
import com.doublefish.doublefishrobot.ui.home.s5.S5ModeMenuActivity;
import com.doublefish.doublefishrobot.utils.AppCacheUtil;
import com.doublefish.doublefishrobot.utils.MessageEvent;
import com.doublefish.doublefishrobot.utils.ToastUtil;
import com.doublefish.doublefishrobot.utils.ble.bean.ModeConstant;
import com.doublefish.doublefishrobot.utils.db.DataBaseApi;
import com.doublefish.doublefishrobot.utils.socket.SocketManager;
import com.doublefish.doublefishrobot.widget.CommonDialog;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者:dugaofeng on 2024/12/17 11:20
 */
public class DevicesBindWifiActivity extends BaseActivity {

    @BindView(R.id.tv_title)
    TextView titleTV;

    @BindView(R.id.tv_right)
    TextView rightTV;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private  int deviceType;

    private AddDeviceListAdapter adapter;
    private List<DeviceBean> searchList = new ArrayList<>(); //已搜索设备列表
    private List<DeviceBean> bindList = new ArrayList<>(); //已绑定设备列表

    private List<AddDeviceListAdapter.BleDeviceEntity> showList = new ArrayList<>();

    //跳转
    public static Intent makeIntent(Context packageContext, int deviceType) {
        Intent intent = new Intent(packageContext, DevicesBindWifiActivity.class);
        intent.putExtra("deviceType", deviceType);
        return intent;
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_device_bind_wifi;
    }

    @Override
    protected void initView() {

        adapter = new AddDeviceListAdapter(this, showList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                AddDeviceListAdapter.BleDeviceEntity entity = showList.get(position);
                if (entity.isHeader() || entity.isBind()) {
                    return;
                }
                if (position == 1 && entity.getDeviceBean() == null) {
                    showEmptyAlert();
                    return;
                }
                saveDevice(entity.getDeviceBean());
            }
        });
    }

    @Override
    protected void initListener() {
        rightTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getWifiList();
            }
        });
        rightTV.setBackground(getResources().getDrawable(R.mipmap.icon_refresh_2));
    }

    @Override
    protected void initData() {
        deviceType = getIntent().getIntExtra("deviceType", 0);
        if (deviceType == ModeConstant.DeviceTypeS5) {
            titleTV.setText(R.string.super_5_robot);
        } else if (deviceType == ModeConstant.DeviceTypeS3) {
            titleTV.setText(R.string.super_3_robot);
        } else {
            showToast(getString(R.string.unknown_device));
            return;
        }

        filterDeviceWithType(deviceType);
        generateShowList();

        getWifiList();
    }

    @OnClick(R.id.ll_back)
    public void onBackClick() {
        finish();
    }

    private void saveDevice(DeviceBean deviceBean) {
        DataBaseApi.saveDeviceInfo(deviceBean, new DataBaseApi.OnDatabaseCommonListner() {
            @Override
            public void onCallback(boolean suc) {
                if (suc) {
                    showToast(getString(R.string.success_added));
                    searchList.remove(deviceBean);
                    bindList.add(0, deviceBean);
                    generateShowList();

                    EventBus.getDefault().post(new MessageEvent(MessageEvent.BIND_DEVICES_CHANGED_NOTI, null));
                    showBindResultAlert(deviceBean);
                }
            }
        });
    }

    private void showBindResultAlert(DeviceBean deviceBean) {
        String title = getString(R.string.success_added);
        String msg = getString(R.string.connect_serve_alert);
        CommonDialog dialog = new CommonDialog(this, title, msg, new CommonDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    //连接发球机
                    connectWifiDevice(deviceBean);
                }
            }
        });
        dialog.setNegativeButton(getString(R.string.cancel));
        dialog.setPositiveButton(getString(R.string.connect));
        dialog.show();
    }

    private void showEmptyAlert() {
        String title = getString(R.string.no_wifi_tips);
        String msg = getString(R.string.wifi_help_tips);
        CommonDialog dialog = new CommonDialog(this, title, msg, new CommonDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    getWifiList();
                }
            }
        });
        dialog.setNegativeButton(getString(R.string.cancel));
        dialog.setPositiveButton(getString(R.string.refresh));
        dialog.show();
    }

    private void disConnect() {
        SocketManager.getInstance().disConnectSocket();
    }

    private void getWifiList() {
        if (!SocketManager.getInstance().isWifiEnabled()) {
            ToastUtil.showToast(this, getString(R.string.please_open_wlan));
            return;
        }
        //wifi扫描 需要定位功能
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            ToastUtil.showToast(this, getString(R.string.require_location_tips));
            return;
        }
        //清空数据
        searchList.clear();

        SocketManager.getInstance().scanWifi(deviceType ,new SocketManager.OnScanWifiCallback() {
            @Override
            public void onScanResults(boolean suc, List<DeviceBean> list) {
                if (suc) {
                    filterDeviceBeanList(list);
                }
            }
        });
    }

    private void filterDeviceBeanList(List<DeviceBean> deviceBeanList) {
        if (deviceBeanList == null || deviceBeanList.size() == 0) {
            return;
        }
        //过滤掉已显示的设备
        for (DeviceBean search : deviceBeanList) {
            DeviceBean bean = beanDidShow(search);
            if (bean != null) {
                searchList.add(bean);
            }
        }
        generateShowList();
        adapter.notifyDataSetChanged();
    }


    //已绑定返回null，否则返回DeviceBean
    private DeviceBean beanDidShow(DeviceBean bean) {
        if (!searchList.isEmpty()) {
            for (DeviceBean search : searchList) {
                if (search.getName().equals(bean.getName())) {
                    return null;
                }
            }
        }

        if (!bindList.isEmpty()) {
            for (DeviceBean bind : bindList) {
                if (bind.getName().equals(bean.getName())) {
                    return null;
                }
            }
        }
        return bean;
    }

    private void filterDeviceWithType(int deviceType) {
        List<DeviceBean> list = AppCacheUtil.getInstance().getBindList();
        if (list == null || list.size() == 0) {
            return;
        }
        for (DeviceBean deviceBean : list) {
            if (deviceBean.getDeviceType() == deviceType) {
                bindList.add(deviceBean);
            }
        }
    }

    private void generateShowList() {
        showList.clear();

        AddDeviceListAdapter.BleDeviceEntity header = new AddDeviceListAdapter.BleDeviceEntity(true);
        header.setTitle(getString(R.string.unbind_device));
        header.setBind(false);
        showList.add(header);

        if (searchList.size() > 0) {
            for (DeviceBean bean:searchList) {
                AddDeviceListAdapter.BleDeviceEntity entity = new AddDeviceListAdapter.BleDeviceEntity(false);
                entity.setDeviceBean(bean);
                entity.setBind(false);
                showList.add(entity);
            }
        } else {
            AddDeviceListAdapter.BleDeviceEntity entity = new AddDeviceListAdapter.BleDeviceEntity(false);
            entity.setDeviceBean(null);
            entity.setBind(false);
            showList.add(entity);
        }

        if (bindList.size() > 0){
            AddDeviceListAdapter.BleDeviceEntity header1 = new AddDeviceListAdapter.BleDeviceEntity(true);
            header1.setTitle(getString(R.string.bond_device));
            header1.setBind(true);
            showList.add(header1);

            for (DeviceBean bean:bindList) {
                AddDeviceListAdapter.BleDeviceEntity entity = new AddDeviceListAdapter.BleDeviceEntity(false);
                entity.setDeviceBean(bean);
                entity.setBind(true);
                showList.add(entity);
            }
        }
        adapter.notifyDataSetChanged();
    }

    //region wifi相关
    private void connectWifiDevice(DeviceBean deviceBean) {
        if (!SocketManager.getInstance().isWifiEnabled()) {
            ToastUtil.showToast(this, getString(R.string.please_open_wlan));
            return;
        }
        SocketManager.getInstance().connectDevice(deviceBean, new SocketManager.OnDeviceConnectListner() {
            @Override
            public void willConnectSocket() {
                //fixme 2025-5-26 Android 连接WIFI有自己的弹窗。
                // 然后， 连接socket很快，不需要loadingdialog
//                showLoadingDialog();
//                hideLoadingDialogDelay5000();
            }

            @Override
            public void onConnect(boolean suc, String msg) {
                if (suc) {
                    //记录当前连接的是超3还是超5 方便自定义的时候保存
                    AppCacheUtil.getInstance().setS3Ors5Type(deviceType);
                    //前往菜单
                    toModeMenuActivity();
                } else {
                    ToastUtil.showToast(DevicesBindWifiActivity.this, msg);
                }
                Log.i("connectWifiDevice", "" + suc);
            }
        });
    }

    private void toModeMenuActivity() {
        Intent intent = new Intent(this, S5ModeMenuActivity.class);
        startActivity(intent);
    }
}
